package com._9xcloud.leaverequest.service;

import com._9xcloud.leaverequest.domain.Course;
import com._9xcloud.leaverequest.domain.Student;
import com._9xcloud.leaverequest.domain.Subject;
import com._9xcloud.leaverequest.domain.Teacher;
import com._9xcloud.leaverequest.exception.NotFoundException;
import com._9xcloud.leaverequest.repository.CourseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

/**
 * Created by hyq on 2015/5/25.
 */
@Repository
@Transactional
public class CourseServiceImpl implements CourseService {
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private CourseRepository courseRepository;

    @Transactional(readOnly = true)
    public Course getById(int courseId) {
        Course course = courseRepository.findOne(courseId);
        if (course == null) {
            throw new NotFoundException("Could not find the course");
        }
        return course;
    }

    @Transactional(readOnly = true)
    public Set<Course> getByStudentId(int studentId) {
        Student student = studentService.getById(studentId);
        return student.getCourses();
    }

    @Transactional(readOnly = true)
    public Set<Course> getByTeacherId(int teacherId) {
        Teacher teacher = teacherService.getById(teacherId);
        return teacher.getCourses();
    }

    public Course create(Subject subject, Teacher teacher, String address) {
        Course course = new Course(subject, teacher, address);
        return courseRepository.saveAndFlush(course);
    }

    @Transactional(readOnly = true)
    public List<Course> getAll() {
        return courseRepository.findAll();
    }

    public void update(Course course) {
        courseRepository.saveAndFlush(course);
    }

    public void removeAll() {
        courseRepository.deleteAll();
        courseRepository.flush();
    }
}
